package com.ztgf.commodity.api.cms;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ztgf.commodity.models.bo.CommodityAdminCategoryAddBO;
import com.ztgf.commodity.models.bo.CommodityCategoryBO;
import com.ztgf.commodity.models.bo.CommodityCategorySaveBO;
import com.ztgf.commodity.models.bo.CommodityCategoryUpdateBO;
import com.ztgf.commodity.models.dto.CommodityCategoryDTO;
import com.ztgf.commodity.models.service.ICategoryImportService;
import com.ztgf.commodity.models.service.ICommodityCategoryService;
import com.ztgf.commodity.models.vo.*;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.common.utils.ExcelExport2;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * author: chenyu.wang
 * date: 2020-05-25 11:28
 * Description:
 */
@RestController
@RequestMapping("/cms/commodityCategory")
@Slf4j
@Api(value = "CommodityCategoryController", tags = "商品分类表cms接口")
public class CommodityCategoryController {

    @DubboReference
    private ICommodityCategoryService categoryService;
    @DubboReference
    private ICategoryImportService categoryImportService;

    @PostMapping(value = "/insert")
    @ApiOperation(value = "添加商品分类表", notes = "添加商品分类表")
    public Result insertCategory(CommodityAdminCategoryAddBO saveBO) {
        return categoryService.addNewCategory(saveBO);
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改商品类目表", notes = "修改商品类目表")
    public Result updateCategory(CommodityCategorySaveBO saveBO) {
        if (null == saveBO.getId()) {
            return new Result<>(CodeEnum.FAIL_100002);
        } else {
            return categoryService.updateNewCategory(saveBO);
        }
    }

    @PostMapping("/getById")
    @ApiOperation(value = "根据id查找商品类目表", notes = "根据id查找商品类目表")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
    public Result getById(Long id) {
        if (null == id) {
            return new Result<>(CodeEnum.FAIL_100002);
        } else {
            CategoryAdminDetailsNewVO details = categoryService.queryCategoryDetails(id);
            return new Result<>(details);
        }

    }

    @PostMapping("/queryPageList")
    @ApiOperation(value = "商品类目列表", notes = "商品类目列表")
    public Result queryPageList(CommodityCategoryBO categoryBO) {
        if (categoryBO.getParentId() == null) {
            categoryBO.setParentId(0L);
        }
        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(categoryBO.getName())) {
            wrapper.like("name", categoryBO.getName());
        } else {
            wrapper.eq("parent_id", categoryBO.getParentId());
        }
        wrapper.orderBy("sort", true); //默认升序
        Page<CommodityCategoryDTO> page = new Page<>(categoryBO.getPageNo(), categoryBO.getPageSize());
        page = categoryService.selectPage(page, wrapper);
        Page<CommodityCategoryTreeVO> pageNew = new Page<>(categoryBO.getPageNo(), categoryBO.getPageSize());
        List<CommodityCategoryTreeVO> real = new ArrayList<>();
        List<CommodityCategoryDTO> list = page.getRecords();
        if (null != list && list.size() > 0) {
            for (CommodityCategoryDTO dto : list) {
                CommodityCategoryTreeVO treeVO = new CommodityCategoryTreeVO();
                treeVO.setId(dto.getId());
                treeVO.setName(dto.getName());
                treeVO.setInitials(dto.getInitials());
                treeVO.setParentId(dto.getParentId());
                treeVO.setSort(dto.getSort());
                treeVO.setJdFlag(dto.getJdFlag());
                treeVO.setJdCode(dto.getJdCode());
                treeVO.setCode(dto.getCode());
                treeVO.setIsDisplayNavBar(dto.getIsPublish());
                real.add(treeVO);
            }
            pageNew.setRecords(real);
            pageNew.setTotal(page.getTotal());
            return new Result<>(pageNew);
        }
        return new Result<>(page);
    }

    @PostMapping("/queryCategoryTree")
    @ApiOperation(value = "商品类目树形结构", notes = "商品类目树形结构")
    public Result queryCategoryTree() {
        List<CommodityCategoryTreeVO> list = categoryService.queryAdminCategoryTree();
        return new Result<>(list);
    }

    @PostMapping("/queryAdminBrokerageList")
    @ApiOperation(value = "后台管理系统佣金管理列表", notes = "后台管理系统佣金管理列表")
    public Result queryAdminBrokerageList(CommodityCategoryBO bo) {
        Page<CommodityCategoryBrokerageVO> list = categoryService.queryAdminBrokerageList(bo);
        return new Result<>(list);
    }

    @PostMapping("/updateTechnicalRatesInBatches")
    @ApiOperation(value = "后台管理系统佣金管理批量设置技术服务费率", notes = "后台管理系统佣金管理批量设置技术服务费率")
    public Result updateTechnicalServiceRatesInBatches(String ids, BigDecimal num,String date) {
        if (StringUtils.isNotBlank(ids)) {
            boolean flag = categoryService.updateTechnicalServiceRatesInBatches(ids, num,date);
            if (flag) {
                return new Result<>();
            } else {
                return new Result<>(CodeEnum.FAIL_100008);
            }
        } else {
            return new Result<>(CodeEnum.FAIL_100002);
        }
    }

//    @PostMapping("/updateEffectiveTime")
//    @ApiOperation(value = "后台管理系统佣金管理批量设置生效时间", notes = "后台管理系统佣金管理批量设置生效时间")
//    public Result updateEffectiveTime(String ids, String date) {
//        if (StringUtils.isNotBlank(ids)) {
//            boolean flag = categoryService.updateEffectiveTime(ids, date);
//            if (flag) {
//                return new Result<>();
//            } else {
//                return new Result<>(CodeEnum.FAIL_100008);
//            }
//        } else {
//            return new Result<>(CodeEnum.FAIL_100002);
//        }
//    }

    @PostMapping("/updateDividendScaleInBatches")
    @ApiOperation(value = "后台管理系统佣金管理批量设置(包括比例和时间)", notes = "后台管理系统佣金管理批量设置(包括比例和时间)")
    public Result updateDividendScaleInBatches(CommodityCategoryUpdateBO bo) {
        if (StringUtils.isEmpty(bo.getIds()) || bo.getDividendScale() == null || bo.getType() == null) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        boolean flag = categoryService.updateDividendScaleInBatches(bo);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }

    }

    @PostMapping("/getBrokerageById")
    @ApiOperation(value = "后台管理系统佣金管理查看详情", notes = "后台管理系统佣金管理查看详情")
    @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "query", dataType = "Long")
    public Result<CommodityCategoryDTO> getBrokerageById(Long id) {
        if (null == id) {
            return new Result<>(CodeEnum.FAIL_100002);
        } else {
            CommodityCategoryDTO dto = categoryService.selectById(id);
            return new Result<>(dto);
        }
    }

    @PostMapping("/getByChildId")
    @ApiOperation(value = "查询类目父级", notes = "查询类目父级")
    public Result getByChildId(Long id) {
        List<CommodityCategoryTreeVO> list = categoryService.getByChildId(id, new ArrayList<>());
        return new Result<>(list);
    }

    @PostMapping("/queryAllZeroLevelCategories")
    @ApiOperation(value = "查询所有0级类目", notes = "查询所有0级类目")
    public Result queryAllZeroLevelCategories() {
        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("status", 0);
        wrapper.eq("is_publish", 1);
        wrapper.eq("parent_id", 0);
        wrapper.orderBy("sort", true);
        return new Result<>(categoryService.selectList(wrapper));
    }

    @PostMapping("/queryCategoryByParentId")
    @ApiOperation(value = "根据父级类目id查询下一级", notes = "根据父级类目id查询下一级")
    public Result queryCategoryByParentId(Long id) {
        Wrapper<CommodityCategoryDTO> wrapper = new EntityWrapper<>();
//        wrapper.eq("status", 0);
//        wrapper.eq("is_publish", 1);
        wrapper.eq("parent_id", id);
        wrapper.orderBy("sort", true);
        List<CommodityCategoryDTO> list = categoryService.selectList(wrapper);
        return new Result<>(list);
    }

    @PostMapping("/getTreeById")
    @ApiOperation(value = "根据0级类目id组装树形结构，平台装修页使用", notes = "根据0级类目id组装树形结构，平台装修页使用")
    public Result test(Long id) {
        List<CommodityCategoryTreeVO> list = categoryService.getTreeByIds(id);
        return new Result<>(list);
    }


    @PostMapping("/getCheckCategory")
    @ApiOperation(value = "判断一个类目是否处于最低级", notes = "判断一个类目是否处于最低级")
    public Result getCheckCategory(Long id) {
        if (null == id) {
            return new Result<>(CodeEnum.FAIL_100002);
        } else {
            Integer flag = categoryService.getCheckCategory(id);
            return new Result<>(flag);
        }
    }

    @PostMapping("/updateIsPush")
    @ApiOperation(value = "后台管理系统修改导航栏是否显示", notes = "后台管理系统修改导航栏是否显示")
    public Result updateIsPush(Long id, Integer state) {
        if (null == id) {
            return new Result<>(CodeEnum.FAIL_100002);
        } else {
            boolean flag = categoryService.updateIsPush(id, state);
            return new Result<>(flag);
        }
    }

    @SneakyThrows
    @PostMapping(value = "/importAttributes")
    @ApiOperation(value = "后台类目管理导入属性返回导入的信息", notes = "后台类目管理导入属性返回导入的信息")
    public Result importAttributes(@RequestParam("file") MultipartFile file, Long id) {
        if (null == file || file.isEmpty()) {
            return new Result<>(CodeEnum.FAIL_FILE_400000);
        }
        if (null == id) {
            return new Result<>(CodeEnum.FAIL_100002);
        }
        byte[] input = file.getBytes();
        CategoryAdminDetailsNewVO result = categoryImportService.importCategoryAttribute(input, id);
        return new Result<>(result);
    }

    @PostMapping("/queryAllFirstLevelCategories")
    @ApiOperation(value = "查询所有一级类目", notes = "查询所有一级类目")
    public Result queryAllFirstLevelCategories() {
        List<CommodityCategoryDTO> list = categoryService.queryAllFirstLevelCategories();
        return new Result<>(list);
    }

    @GetMapping(value = "/exportAllCategoryList")
    @ApiOperation(value = "导出全部类目属性", notes = "导出全部类目属性")
    public void batchExportGoodsList(HttpServletResponse response) {
        //创建一个数组用于设置表头
        String[] attributeNames = new String[]{"序号", "零级类目", "一级类目", "二级类目", "三级类目", "品牌名称", "单位属性", "销售属性", "参数属性", "标签属性"};
        // 查询类目
        List<CategoryExportVO> list = categoryService.getCategoryExportDate();
        if (CustomizeUtil.listIsNotNull(list)) {
            ExcelExport2.export(response, list, attributeNames, "_全部类目属性");
        } else {
            List<CategoryExportVO> errorList = new ArrayList<>();
            CategoryExportVO vo = new CategoryExportVO();
            vo.setSerialNumber(1);
            vo.setZeroLevelName("暂无数据");
            vo.setOneLevelName("暂无数据");
            vo.setTwoLevelName("暂无数据");
            vo.setThreeLevelName("暂无数据");
            vo.setBrandName("暂无数据");
            vo.setUnitAttribute("暂无数据");
            vo.setSalesAttribute("暂无数据");
            vo.setParameterAttribute("暂无数据");
            vo.setLabelAttribute("暂无数据");
            errorList.add(vo);
            ExcelExport2.export(response, errorList, attributeNames, "_全部类目属性");
        }
    }


}
